package com.warehouse.controller;

import com.warehouse.common.Result;
import com.warehouse.dto.ProductDTO;
import com.warehouse.entity.Product;
import com.warehouse.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
@CrossOrigin(origins = "*")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping
    public Result<List<Product>> getAllProducts() {
        List<Product> products = productService.getAllProducts();
        return Result.success(products);
    }

    @GetMapping("/with-box-display")
    public Result<List<ProductDTO>> getAllProductsWithBoxDisplay() {
        List<ProductDTO> products = productService.getAllProductsWithBoxDisplay();
        return Result.success(products);
    }

    @GetMapping("/{id}")
    public Result<Product> getProductById(@PathVariable Long id) {
        Product product = productService.getProductById(id);
        if (product != null) {
            return Result.success(product);
        }
        return Result.error("商品不存在");
    }

    @GetMapping("/category/{category}")
    public Result<List<Product>> getProductsByCategory(@PathVariable String category) {
        List<Product> products = productService.getProductsByCategory(category);
        return Result.success(products);
    }

    @GetMapping("/search")
    public Result<List<Product>> searchProducts(@RequestParam String productName) {
        List<Product> products = productService.getProductsByName(productName);
        return Result.success(products);
    }

    @GetMapping("/low-stock")
    public Result<List<Product>> getLowStockProducts() {
        List<Product> products = productService.getLowStockProducts();
        return Result.success(products);
    }

    @PostMapping
    public Result<Product> createProduct(@RequestBody Product product) {
        Product createdProduct = productService.createProduct(product);
        return Result.success(createdProduct);
    }

    @PutMapping("/{id}")
    public Result<Product> updateProduct(@PathVariable Long id, @RequestBody Product product) {
        product.setId(id);
        Product updatedProduct = productService.updateProduct(product);
        return Result.success(updatedProduct);
    }

    @PutMapping("/{id}/stock")
    public Result<Boolean> updateStock(@PathVariable Long id, @RequestParam Integer quantity) {
        boolean success = productService.updateStock(id, quantity);
        if (success) {
            return Result.success(true);
        }
        return Result.error("更新库存失败");
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteProduct(@PathVariable Long id) {
        boolean success = productService.deleteProduct(id);
        if (success) {
            return Result.success(true);
        }
        return Result.error("删除商品失败");
    }
} 